package IO;

import java.io.File;
import java.util.Scanner;

public class IODemo9 {
    // 搜索指定的文件,如果有询问用户是否删除
    public static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.print("请输入要搜索的路径:");
        String basePath = scanner.next();

        File root = new File(basePath);
        
        if (!root.isDirectory()){
            System.out.println("输入目录有误!");
            return;
        }

        System.out.print("请输入要删除的文件名:");
        String nameToDelete = scanner.next();
        
        scanDir(root,nameToDelete);
        
    }

    private static void scanDir(File root, String nameToDelete) {
        System.out.println("[scanDir]" + root.getAbsolutePath());
        File[] files = root.listFiles();

        if (files == null){
            return;
        }

        for (File f : files){
            if (f.isDirectory()){
                scanDir(f,nameToDelete);
            }else {
                // contains()方法用于 判断字符串中是否包含指定的字符或字符串
                if (f.getName().equals(nameToDelete)){
                    System.out.println("确定要删除"+ f.getAbsolutePath() + "吗? (yes/no)");
                    System.out.print("> ");
                    String ret = scanner.next();
                    if (ret.equals("yes")){
                        f.delete();
                        System.out.println("删除成功!");
                    }else {
                        System.out.println("已取消删除!");
                    }
                }
            }
        }
    }

}
